// pages/enterprise/user/info/index.js
import Config from "../../../main.config";
import {chooseImage, requestSubscribeMessage} from "../../../utils/Wx";
import {isInputEmpty} from "../../../utils/Util";
import {getDictList, uploader} from "../../../service/Common";
import {getRegisterDetail, createUser, editUser} from "../../../service/Enterprise";
import {getStorageSync, setStorageSync} from "../../../utils/Storage";
import Notify from "@vant/weapp/notify/notify";
import Toast from "@vant/weapp/toast/toast";
import Dialog from "@vant/weapp/dialog/dialog";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        /*--表单数据--*/
        logo: {
            id: "",
            src: ""
        },
        name: "", //企业名称
        scale: {
            title: "企业规模",
            value: "",
            list: [],
            current: 0
        },
        nature: {
            title: "企业性质",
            value: "",
            list: [],
            current: 0
        },
        industry: {
            title: "企业行业",
            id: "",
            value: ""
        },
        city: "", //所在城市
        addressDetail: "", //地址详细
        introduction: "", //企业概述

        /*--组件数据--*/
        picker: { //选择器
            show: false,
            loading: false,
            name: "", //选择器名称
            title: "",  //选择器标题
            list: [],
            defaultIndex: 0
        },
        region: { //区域选择器
            loading: false,
            show: false,
            value: ""
        },
        isLoading: false // 按钮状态
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.todo !== "create") { //新用户 没有用户信息 不需要调用
            this.getCompanyDetail();
        }
    },

    /*
    * 获取企业详情
    * */
    getCompanyDetail: async function () {
        try {
            let userId = getStorageSync(Config.storage.userInfo + ".userId");
            let res = await getRegisterDetail({createUser: userId});
            this.data._enterpriseDetail = res;
            res ? this.setData({
                "logo.id": res.logo,
                "logo.src": Config.api.downLoad + "?fileId=" + res.logo,
                name: res.name,
                "scale.value": res.scale,
                "nature.value": res.nature,
                "industry.value": res.industryName,
                "industry.id": res.industryNo,
                city: res.city.split(",")[1],
                addressDetail: res.addressDetail,
                introduction: res.introduction,
                "region.value": res.city
            }) : null
        } catch (e) {
            console.error(e)
        }
    },

    /*
    * 图片上传
    * */
    bindUploaderLogo: async function () {
        try {
            let tempFilePaths = await chooseImage();
            Toast.loading({
                message: "图片上传中...",
                duration: 0
            });
            this.data.logo.id = await uploader(tempFilePaths[0]);
            this.setData({"logo.src": tempFilePaths});
            Toast.clear();
        } catch (e) {
            e.errMsg !== "chooseImage:fail cancel" ? Toast.fail("上传失败") : null;
            console.error(e)
        }
    },

    /*
    * input 输入监听
    * */
    onInput: function (e) {
        let name = e.currentTarget.dataset.name;
        let value = e.detail
        this.setData({[name]: value})
    },

    /*
    * 选择行业
    * */
    bindNavigateToIndustrySearch: function () {
        const that = this;
        wx.navigateTo({
            url: "/pages/common/industry-search/index",
            events: {
                acceptDataFromOpenedPage: function(data) {
                    console.log(data)
                    that.setData({
                        "industry.value": data.industryName,
                        "industry.id": data.industryNo
                    })
                }
            },
        })
    },

    /*
    * 选择器展开
    * */
    bindShowPicker: async function (e) {
        try {
            const that = this;
            let name = e.currentTarget.dataset.name;
            let title = this.data[name].title;
            let list = this.data[name].list;
            let current = this.data[name].current;
            this.setData({"picker.show": true});
            if (list && list.length === 0) { //没有数据的情况下
                this.setData({"picker.loading": true});
                switch (name) {
                    case "scale": //企业规模
                        list = await getDictList("QYGM");
                        break
                    case "nature": //企业性质
                        list = await getDictList("QYXZ");
                        break
                    // case "industry": //企业行业
                    //     list = await getIndustryList();
                    //     break
                }
                this.data[name].list = list;
            }
            this.setData({
                "picker.loading": false,
                "picker.name": name,
                "picker.title": title,
                "picker.list": list
            }, function () {
                that.setData({"picker.defaultIndex": current})
            })
        } catch (e) {
            console.error(e)
        }
    },
    // 选择器选择
    onPickerConfirm: function (e) {
        let name = e.currentTarget.dataset.name;
        let detail = e.detail;
        this.setData({
            "picker.show": false,
            [name + ".value"]: detail.value.text
        })
        this.data[name].id = detail.value.value;
        this.data[name].current = detail.index;
    },
    // 选择器关闭
    onPickerCancel: function (e) {
        this.setData({"picker.show": false})
    },

    /*
    * 获取定位信息
    * */
    getLocationRegion: function () {
        this.setData({"region.loading": true});
    },
    onLocation: function (e) {
        let detail = e.detail;
        if (Object.keys(detail).length > 0) {
            this.setData({
                "region.value": detail.region,
                city: detail.region.split(",")[1],
                addressDetail: detail.address
            })
        } else {
            this.setData({"region.show": true})
        }
    },
    // 区域选择
    onSelectRegion: function (e) {
        let detail = e.detail;
        this.setData({"region.show": false});
        if (!detail) return false;
        this.setData({
            "region.value": detail,
            city: detail.split(",")[1]
        })
    },

    /*
    * 跳转富文本编辑页面
    * */
    bindNavigatorToRichText: function () {
        const that = this;
        let introduction = this.data.introduction;
        setStorageSync(Config.storage.richText, introduction);
        wx.navigateTo({
            url: "/pages/common/rich-text/index?from=info",
            events: {
                acceptDataFromOpenedPage: function(data) {
                    that.setData({introduction: data})
                }
            },
        })
    },

    /*
    * 点击保存按钮
    * 如果是从用户中心跳过来  直接返回
    * 如果是其它页面过来 关闭所有页面跳转目标页
    * 为了防止 可以连续返回
    * */
    onSubmitButton: async function () {
        try {
            let isLoading = this.data.isLoading;
            let logo = this.data.logo.id;
            let name = this.data.name;
            let scale = this.data.scale.value;
            let nature = this.data.nature.value;
            let industryName = this.data.industry.value;
            let industryNo = this.data.industry.id;
            let city = this.data.region.value;
            let addressDetail = this.data.addressDetail;
            let introduction = this.data.introduction;
            if (isLoading) { //防重复
                return false
            } else if (!logo) {
                Notify("请上传企业logo");
                return false
            } else if (!isInputEmpty(name)) {
                Notify("请填写企业名称");
                return false
            } else if (!scale) {
                Notify("请选择企业规模");
                return false
            } else if (!nature) {
                Notify("请选择企业性质");
                return false
            } else if (!industryName) {
                Notify("请选择所属行业");
                return false
            } else if (!city) {
                Notify("请选择所在地");
                return false
            } else if (!addressDetail) {
                Notify("请填写详细地址");
                return false
            } else if (!introduction) {
                Notify("请填写企业简介");
                return false
            } else {
                let enterpriseDetail = this.data._enterpriseDetail;
                let enterpriseId = enterpriseDetail ? enterpriseDetail.id : null;
                let postData = {
                    logo,
                    name,
                    scale,
                    nature,
                    industryName,
                    industryNo,
                    city,
                    addressDetail,
                    introduction
                }
                this.setData({isLoading: true});
                await requestSubscribeMessage([Config.templateId.qysq]);
                if (enterpriseId) { //编辑
                    await Dialog.confirm({
                        title: "提示！",
                        message: "修改企业信息需要再次审核"
                    })
                    postData.id = enterpriseId;
                    await editUser(postData);
                } else {
                    await createUser(postData);
                }
                Toast.success("保存成功");
                setTimeout(function () {
                    wx.reLaunch({url: "/packageEnterprise/pages/status/index?status=1"})
                }, 1500)
            }
        } catch (e) {
            console.error(e)
        } finally {
            this.setData({isLoading: false});
        }
    }
})